﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.Security;
using System.Collections.Generic;
using System.Linq;

namespace SPCIT.SP2010.Portal.MapMembershipUserToRole
{
    [ToolboxItemAttribute(false)]
    public class MapMembershipUserToRole : SPCITProvidersBaseWebPart
    {
        protected DropDownList loginNames;
        protected CheckBoxList roles;

        protected Button confirmCommand;
        protected Label result;

        protected override void CreateChildControls()
        {
            this.loginNames = new DropDownList();
            this.loginNames.AutoPostBack = true;
            this.loginNames.SelectedIndexChanged += new EventHandler(loginNames_SelectedIndexChanged);
            this.Controls.Add(this.loginNames);

            this.roles = new CheckBoxList();
            this.Controls.Add(this.roles);

            this.confirmCommand = new Button();
            this.confirmCommand.Click += new EventHandler(confirmCommand_Click);
            this.confirmCommand.Text = "Conferma";
            this.Controls.Add(this.confirmCommand);

            this.result = new Label();
            this.result.Text = String.Empty;
            this.Controls.Add(this.result);

            base.CreateChildControls();
        }

        protected override void OnLoad(EventArgs e)
        {
            this.EnsureChildControls();

            base.OnLoad(e);

            SPWeb webContext = SPControl.GetContextWeb(Context);

            if ((!this.Page.IsPostBack) 
                    && (webContext.CurrentUser != null)
                    && (webContext.CurrentUser.IsSiteAdmin))
                {
                bindLoginNames();
                bindRoles();
            }
        }

        private void bindRoles()
        {
            this.roles.Items.Clear();
            this.roles.DataSource = this.GetConfiguredRoleProvider().GetAllRoles();
            this.roles.DataBind();

            foreach (ListItem roleItem in this.roles.Items)
            {
                if (this.GetConfiguredRoleProvider().IsUserInRole(this.loginNames.SelectedValue, roleItem.Value))
                {
                    roleItem.Selected = true;
                }
            }
        }

        private void bindLoginNames()
        {
            this.loginNames.Items.Clear();
            Int32 totalRecords;
            this.loginNames.DataSource = this.GetConfiguredMembershipProvider().GetAllUsers(0, Int32.MaxValue, out totalRecords);
            this.loginNames.DataValueField = "UserName";
            this.loginNames.DataTextField = "UserName";
            this.loginNames.DataBind();
        }

        void loginNames_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.bindRoles();
        }

        void confirmCommand_Click(object sender, EventArgs e)
        {
            SPWeb webContext = SPControl.GetContextWeb(Context);

            if ((webContext != null)
                && (webContext.CurrentUser != null)
                && (webContext.CurrentUser.IsSiteAdmin))
            {
                try
                {
                    if (this.GetConfiguredRoleProvider() != null)
                    {
                        List<String> rolesToMap = new List<String>();

                        foreach (ListItem roleItem in this.roles.Items)
                        {
                            if (roleItem.Selected)
                            {
                                rolesToMap.Add(roleItem.Value);
                            }
                        }

                        String[] currentUserRoles = this.GetConfiguredRoleProvider().GetRolesForUser(this.loginNames.SelectedValue);
                        if (currentUserRoles.Length > 0)
                            this.GetConfiguredRoleProvider().RemoveUsersFromRoles(new String[] { this.loginNames.SelectedValue }, currentUserRoles);

                        String[] roleNames = rolesToMap.Except(this.GetConfiguredRoleProvider().GetRolesForUser(this.loginNames.SelectedValue)).ToArray();
                        if (rolesToMap.Count > 0)
                            this.GetConfiguredRoleProvider().AddUsersToRoles(new String[] { this.loginNames.SelectedValue }, rolesToMap.ToArray());
                    }
                    else
                    {
                        this.result.Text = "<BR>Role provider non configurato.";
                    }
                }
                catch (Exception ex)
                {
                    this.result.Text = "<BR>Errore durante il cambiamento dei ruoli.<BR>" + ex.Message + "<BR>" + ex.StackTrace;
                }
            }
            else
            {
                result.Text = "<BR>Utente non abilitato ad eseguire l'operazione!";
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            String loginName = string.Empty;
            SPWeb webContext = SPControl.GetContextWeb(Context);

            try
            {
                loginName = webContext.CurrentUser.LoginName;
            }
            catch (Exception)
            {
                this.result.Text += "<BR>Effettuare l'accesso prima di usare questa WebPart.";
            }

            if (loginName != String.Empty)
            {
                writer.Write("<table border=0>");

                writer.Write("<tr>");
                writer.Write("<td class='ms-vb'>");
                writer.Write("Utente:");
                writer.Write("</td>");
                writer.Write("<td class='ms-vb'>");
                this.loginNames.RenderControl(writer);
                writer.Write("</td>");
                writer.Write("<td class='ms-vb'>");
                writer.Write("</td>");
                writer.Write("</tr>");

                writer.Write("<tr>");
                writer.Write("<td class='ms-vb'>");
                writer.Write("Ruoli:");
                writer.Write("</td>");
                writer.Write("<td class='ms-vb'>");
                this.roles.RenderControl(writer);
                writer.Write("</td>");
                writer.Write("<td class='ms-vb'>");
                writer.Write("</td>");
                writer.Write("</tr>");

                writer.Write("<tr valign='top'>");
                writer.Write("</td>");
                writer.Write("<td class='ms-vb'>");
                writer.Write("</td>");
                writer.Write("<td class='ms-vb'>");
                this.confirmCommand.RenderControl(writer);
                writer.Write("</td>");
                writer.Write("<td class='ms-vb'>");
                writer.Write("</td>");
                writer.Write("</tr>");

                writer.Write("</table>");
                this.result.RenderControl(writer);
            }
            else
            {
                this.result.RenderControl(writer);
            }
        }
    }
}
